<script setup>
import {useApi} from "../../composables/useApi.js"
import showTost from '@/components/toast/index.js'
import {storeToRefs} from "pinia"
import {useAppStore} from "../../store/app.js"

const appStore = useAppStore()

const {nationArr, sexArr} = storeToRefs(appStore)
import {reactive, ref} from "vue"
import StandardGradeDrawear from "@/pages/platform/components/standardGradeDrawear.vue";
import {router} from "@/plugins/1.router/index.js";
import * as XLSX from "xlsx";
import {getStudentList} from "@/api/student.js";
import {standardAddModify, standardDelete} from "@/api/standard.js";
import ModelHeader from "@/pages/platform/components/modelHeader.vue";
import UploadOhterImg from "@/components/uploadOhterImg.vue";
import {medalAddModify, medalDelete, medalRecordAddModify, medalRecordDelete} from "@/api/medal.js";
import MedalDrawear from "@/pages/platform/components/medalDrawear.vue";
import communitySecondDrawear from "@/pages/platform/components/communitySecondDrawear.vue";
import PacketStaffSecondDrawear from "@/pages/platform/components/packetStaffSecondDrawear.vue";
let route = useRoute()

//基本数据list
let list = ref([])
let page = ref(1)
let limit = ref(20)
let total = ref(0)//总数
const selected = ref([])
let queryFrom = ref({page: 1, limit: 20,group_id:route.query.id })

const headers = [
  {
    title: "学生姓名",
    key: "studentName",
    width:"240px",
    align: 'start',
  },
  {
    title: "学生ID",
    width:"240px",
    align: 'start',
    key: "studentId",
  },
  {
    title: "年级",
    width:"240px",
    align: 'start',
    key: "gradeTitle",
  },
  {
    title: "班级",
    width:"240px",
    align: 'start',
    key: "classTitle",
  },


  {
    title: "操作",
    align: 'end',
    width:"240px",
    sortable: false,
    key: "options",
  },
]

const headersRecord = [
  {
    title: "教师姓名",
    key: "teacherName",
    width:"240px",
    align: 'start',
  },
  {
    title: "教师ID",
    width:"240px",
    align: 'start',
    key: "teacher_id",
  },
  {
    title: "教师职位描述",
    width:"240px",
    align: 'start',
    key: "content",
  },
  {
    title: "操作",
    align: 'end',
    width:"240px",
    sortable: false,
    key: "options",
  },
]
const tabsIndex  =ref(0)

const examcourse_id = ref(null)
// todo 复制修改列表接口
const getList = async () => {
  const {data} = await useApi(tabsIndex.value==0?'/admin/Api.GroupStudent/index':'/admin/Api.GroupTeacher/index').post({...queryFrom.value})
  total.value = data.value.data.total
  list.value = data.value.data.data.map(item => {
    return {
      ...item, id: tabsIndex.value===0?item.groupstudent_id:item.groupteacher_id
    }
  })
}
getList()
const dialogFlag = ref(false)
// 头部表单回调
const onChange = val => {
  let data = JSON.parse(JSON.stringify(val))
  queryFrom.value = {...queryFrom.value, ...data}
  getList()
}
const isConfirmDialogVisible = ref(false)
// 删除确认弹窗
const onHandleDelete = async (val) => {
  console.log(val)
  if(tabsIndex.value ==0 ){
    let ids = val.data.map(item => item.groupstudent_id).toString()
    console.log(ids)
    const {data} = await useApi('/admin/Api.GroupStudent/delete').post({group_id:route.query.id,groupstudent_id: ids})
    console.log(data.value)
    if (data.value.status == 200) {
      showTost("删除成功", {duration: 3000, type: "success"})
      queryFrom.value.page = 1
      isConfirmDialogVisible.value = false
      if (val.type == 'detail') {
        dialogFlag.value = false
      }
      getList()
    }
  }else{
    let ids = val.data.map(item => item.groupteacher_id).toString()
    console.log(ids)
    const {data} = await useApi('/admin/Api.GroupTeacher/delete').post({group_id:route.query.id,groupteacher_id: ids})
    console.log(data.value)
    if (data.value.status == 200) {
      showTost("删除成功", {duration: 3000, type: "success"})
      queryFrom.value.page = 1
      isConfirmDialogVisible.value = false
      if (val.type == 'detail') {
        dialogFlag.value = false
      }
      getList()
    }
  }


}
const selectedItems = ref([]);

// 确认弹窗文本
const confirmMsg = ref('')
const currentOptionData = ref({})

// 打开删除弹窗
const onHandleDialog = (type) => {
  if (type == 'delete') {
    console.log(selectedItems)
    if (selectedItems.value.length == 0) return
    let data = list.value.filter(item => selectedItems.value.find(val => val == item.id))
    console.log(data)
    currentOptionData.value = {
      data: data,
      type: 'list'
    }
    confirmMsg.value = `确认删除${tabsIndex.value==0?data.map(item => item.studentName).toString():data.map(item => item.teacherName).toString()}的信息吗?`
    isConfirmDialogVisible.value = true
  } else if (type == 'openSecondPage'){
    router.push( '/platform/times-manage?type=2')
  } else {
    addDialogFlag.value = true
  }
}
// 详情数据
const detailData = ref({})

// 去详情
const viewDetail = async (item) => {
  console.log(item)
  const {data} = await useApi(tabsIndex.value==0?'/admin/Api.GroupStudent/detail':'/admin/Api.GroupTeacher/detail').post({group_id:route.query.id,groupstudent_id: item.groupstudent_id,groupteacher_id:item.groupteacher_id})
  console.log(data)
  detailData.value = data.value.data
  dialogFlag.value = true
}
// 添加教师弹窗falg
const addDialogFlag = ref(false)
const refVForm = ref()

// 下载模板
const downLoadTemplate = async () => {
  const {data} = await useApi('/admin/Base/downFile').post({type: 5})
  console.log(data.value)
  if (data.value.status == 200) {
    const link = document.createElement('a');
    link.href = data.value.data.fileUrl;
    link.download = data.value.data.fileName;
    link.target = "_blank"; // 可选，如果希望在新窗口中下载文件，请取消注释此行
    link.click();
  }
}
// 新增取消回调
const resetForm = () => {
  refVForm.value?.reset()
  addDialogFlag.value = false
}


const valid = ref(false)
const form = reactive({
  class_id:null,
  grade_id:null,
  studentId:null,
})

let totalScore = computed(()=>{
  return Number(form.languageScore)    +  Number(form.mathsScore) + Number(form.englishScore)
})

const confirmAdd = async (args) => {
  console.log(totalScore.value)
  if (!valid.value) return
  if(tabsIndex.value == 0){
    const {data} = await useApi('/admin/Api.GroupStudent/add').post({...form,group_id:route.query.id})
    if (data.value.status == 200) {
      refVForm.value?.reset()
      addDialogFlag.value = false
      showTost("新增成功", {duration: 3000, type: "success"})
      queryFrom.value.page = 1
      getList()
    } else {
      console.log(data.value.msg)
      // showTost("新增成功", {duration: 3000, type: "success"})

      showTost(data.value.msg, {duration: 3000, type: "error"})
    }
  }else{
    const {data} = await useApi('/admin/Api.GroupTeacher/add').post({...form,group_id:route.query.id})
    refVForm.value?.reset()
    addDialogFlag.value = false
    showTost("新增成功", {duration: 3000, type: "success"})
    queryFrom.value.page = 1
    getList()
  }


}
let sexList = ref(['男', '女'])
const onHandleEdit = () => {
  queryFrom.value.page = 1
  getList()
}
// getList()
const required = (value, name) => !!value || `${name}为必填字段`;

const import_page = ref(1)
const import_limit = ref(10)
const import_percent = ref(0)
const loading = ref(false)

const partPost = async (tableData) => {
  let perdata = []
  for (let i = (import_page.value - 1) * import_limit.value; i < import_page.value * import_limit.value; i++) {
    if (tableData[i]) {
      perdata.push(tableData[i])
    }
  }
  let total_page = Math.ceil(tableData.length / import_limit.value)
  import_percent.value = Math.ceil(import_page.value * 100 / total_page)
  loading.value = true
  console.log(perdata)
  const {data} = await useApi('/admin/Api.Standardization/upload').post(JSON.stringify(perdata))
  if (data.value.status == 200) {
    if (import_page.value <= total_page - 1) {
      import_page.value = import_page.value + 1
      partPost(data)
    } else {
      // this.dialog.importDialogstatus = false;
      showTost("导入完成", {duration: 3000, type: "success"})
      loading.value = false
    }
  }
}

const onChangePage = (val) => {
  queryFrom.value.page = val.page
  queryFrom.value.limit = val.limit
  getList()
}
const drawaerDelete = async (val) => {
  console.log(val)
  currentOptionData.value = {
    data: [val],
    type: 'detail'
  }
  confirmMsg.value = `确认删除${tabsIndex.value==0?val.studentName:val.teacherName}的信息吗`
  isConfirmDialogVisible.value = true
}
const viewDetailClassStudent = (type, item)=>{
  showTost('暂未开放')
  if(type =='class'){

  }
}
// 二级页面显示开关
const secondPageShowFlag = ref(false)
const onHandleSecondPage = ()=>{
  secondPageShowFlag.value = true
}
const examTitle = ref('')
const changeId = (val)=>{
  examcourse_id.value = val.id
  examTitle.value =val.title
  getList()
}
const   httpRequest= (e)=> {
  let file = e.file // 文件信息
  if (!file) {
    return false
  } else if (!/\.(xls|xlsx)$/.test(file.name.toLowerCase())) {
    // 格式根据自己需求定义
    this.$message.error('上传格式不正确，请上传xls或者xlsx格式')
    return false
  }
  const fileReader = new FileReader()
  fileReader.onload = (ev) => {
    try {
      const data = ev.target.result
      const workbook = XLSX.read(data, {
        // 以字符编码的方式解析
        type: 'binary',
        cellDates: true,

      })
      // 取第一张表
      console.log(workbook)
      const exlname = workbook.SheetNames[0]
      const exl = XLSX.utils.sheet_to_json(workbook.Sheets[exlname]) // 生成json表格内容
      console.log(exl)
      partPost(exl)
      // 将 JSON 数据挂到 data 里
      let arr = []
      exl.forEach(item => {
        arr.push(item.name)
      })
      console.log(arr)
    } catch (e) {
      console.log('error')
      return false
    }
  }
  fileReader.readAsBinaryString(file)
}

const onlyAllowNumbers = (event) => {
  const key = event.key;
  // 检查按键是否为数字或控制键（如 backspace）
  if (!/^\d$/.test(key) && event.key !== 'Backspace' && event.key !== 'Tab') {
    event.preventDefault();
  }
}
const filterInput =(key) => {
  // 仅保留数字
  form[key] = form[key].replace(/\D/g, '');
}

const projectList = ref(['德','智','体','美','劳'])

const tabsChange = (index)=>{
  tabsIndex.value = index
  list.value = []
  queryFrom.value.page = 1
  getList()
}
/**  获取学生列表*/
const studentList = ref([])
const getStudentListProp = async () => {
  getStudentList({page:1,limit:9999,grade_id:form.grade_id,class_id:form.class_id}).then(res=>{
    studentList.value = res.data.value.data
    console.log(studentList.value)
  })
}
// getStudentListProp()

/** 获取奖章列表不分页*/
const madelList = ref([])
const getMadelList = async () => {
  const {data} = await useApi('/admin/Api.Medal/index').post({page:1,limit:9999})
  madelList.value = data.value.data.data.map(item => {
    return {
      ...item, id: item.medal_id
    }
  })
}
getMadelList()

// 获取教师列表开始
const teacherList = ref([])
const getTeacherList = async () => {
  const {data} = await useApi('/admin/Api.Teacher/indexList').post({})
  if (data.value.status == 200) {
    teacherList.value = data.value.data
  }
}
getTeacherList()
// 获取教师列表结束

/** 顶部切换素质教育/标化成绩tabs功能开始*/

const handleHeaderTabs = (index) => {
  tabsIndex.value = index
  console.log(tabsIndex.value)
//   todo tabs切换数据
  queryFrom.value.page=1
  getList()
}
/** 顶部切换素质教育/标化成绩tabs功能结束*/
// 获取年级列表开始
const gradeList = ref([])
const getGradeList = async () => {
  const {data} = await useApi('/admin/Api.Grade/indexList').post({})
  if (data.value.status == 200) {
    console.log(data.value.data)
    gradeList.value = data.value.data
  }
}
getGradeList()
// 获取年级列表结束
// 班级不分页列表开始
const classList = ref([])
const getClassList = async (id='') => {
  const {data} = await useApi('/admin/Api.GradeClass/indexList').post({grade_id:id})
  if (data.value.status == 200) {
    console.log(data.value.data)
    classList.value = data.value.data
  }
}
getClassList()
// 班级不分页列表结束
const gradeChange = (id)=>{
  if(id!= form.class_id){
    form.class_id = ''
  }
  getClassList(id)
}

const classChange = (id)=>{
  form.studentId = null
  getStudentListProp()

}
</script>

<template>
  <div class="content">
    <!--   Ought to 修改右侧抽屉-->
    <packet-staff-second-drawear :tabs-index="tabsIndex" :madelList="madelList"  :teacher-list="teacherList" @onHandleDelete="drawaerDelete"  @onHandleEdit="onHandleEdit"
                            :detailData="detailData" @update:isDrawerOpen="dialogFlag=$event"
                            :is-drawer-open="dialogFlag" :student-list="studentList"></packet-staff-second-drawear>

    <ConfirmDialog
      :handleData="currentOptionData"
      v-model:isDialogVisible="isConfirmDialogVisible"
      @confirm="onHandleDelete"
      :confirm-msg="confirmMsg"
      :confirmation-question="confirmMsg"
      cancel-msg="Unsubscription Cancelled!!"
    />
    <!--    Ought to 修改顶部检索栏部分-->
    <!-- 头部 -->
    <custom-header :title="route.query.name + '人员管理'"
                   show-back
                   :button-text="tabsIndex==1?'添加职员':'添加学生'"
                   @tabsChange="tabsChange"
                   @onChange="onChange"
                   @changeId="changeId"
                   @onHandle="onHandleDialog">
      <div class="tabs ">
        <div @click="handleHeaderTabs(0)" :class="{item: true, active: tabsIndex === 0}">
          <i  class="ri-open-arm-line"></i>
          学生列表
        </div>
        <div @click="handleHeaderTabs(1)" :class="{item: true, active: tabsIndex === 1}">
          <i class="ri-user-2-line"></i>
          职员列表
        </div>
      </div>
    </custom-header>
    <VDataTable
      v-model="selectedItems"
      :headers="tabsIndex==0?headers:headersRecord"
      :items-per-page="100"
      :items="list"
      item-key="id"
      show-select
      class="text-no-wrap"
    >
      <template #item.options="{ item }">
        <div class="d-flex align-center options-right-display">
          <div class="d-flex flex-column ms-3 cursor-pointer">
            <i @click="viewDetail(item)" class="ri-edit-line"></i>
          </div>
        </div>
      </template>
    </VDataTable>
    <PaginationVue
      @onChange="onChangePage"
      :current-page="queryFrom.page"
      :page-size="queryFrom.limit"
      :total="total"
    />
    <!--    添加对话框-->
    <VDialog
      :persistent="true"
      max-width="600"
      :model-value="addDialogFlag"
    >
      <div class="dialog-body">
        <AppDrawerHeaderSection
          :title="tabsIndex===0?'添加学生':'添加职员'"
          @cancel="addDialogFlag=false"
        />
        <VDivider/>
        <VCard>
          <PerfectScrollbar
            :options="{ wheelPropagation: false }"
            class="h-60"
          >
            <VCardText>

              <VForm
                v-model="valid"
                ref="refVForm"
                @submit.prevent="confirmAdd"
              >
                <VRow v-if="tabsIndex==0">
                  <VCol cols="6">
                    <VTextField
                      v-model="form.studentId"
                      disabled
                      label="学生ID"
                      :rules="[(val)=>required(val,'学生ID')]"
                    >
                      <template v-slot:label>
                        <span>学生ID</span>
                        <span  style="color: red;margin-left: 4px;">*</span>
                      </template>
                    </VTextField>
                  </VCol>
                  <VCol cols="6">

                    <VSelect
                      :items="gradeList"
                      @update:modelValue="gradeChange"
                      v-model="form.grade_id"
                      item-title="title"
                      item-value="grade_id"
                      label="年级"
                    >
                      <template v-slot:label>
                        <span>年级</span>
                        <span  style="color: red;margin-left: 4px;">*</span>
                      </template>
                    </VSelect>
                  </VCol>
                  <VCol cols="6">
                    <VSelect
                      v-model="form.class_id"
                      @update:modelValue="classChange"
                      :items="classList"
                      item-title="title"
                      item-value="class_id"
                      placeholder="请选择所属班级"
                      label="班级"
                      :rules="[(val)=>required(val,'班级')]"
                    >
                      <template v-slot:label>
                        <span>班级</span>
                        <span  style="color: red;margin-left: 4px;">*</span>
                      </template>
                    </VSelect>
                  </VCol>
                  <VCol cols="6">
                    <VAutocomplete
                      v-model="form.studentId"
                      :items="studentList"
                      item-title="real_name"
                      item-value="student_id"
                      :rules="[(val)=>required(val,'学生姓名')]"
                    >
                      <template v-slot:label>
                        <span>学生姓名</span>
                        <span  style="color: red;margin-left: 4px;">*</span>
                      </template>
                    </VAutocomplete>
                  </VCol>
                  <VDivider style="margin-top: 20px"/>
                  <VCol cols="12">
                    <div class="d-flex justify-end">
                      <VBtn
                        type="submit"
                        color="primary"
                        class="me-4"
                      >
                        添加
                      </VBtn>
                    </div>
                  </VCol>
                </VRow>
                <VRow v-if="tabsIndex==1">
                  <VCol cols="6">
                    <VTextField
                      v-model="form.teacher_id"
                      disabled
                      label="教师ID"
                      :rules="[(val)=>required(val,'教师ID')]"
                    >
                      <template v-slot:label>
                        <span>教师ID</span>
                        <span  style="color: red;margin-left: 4px;">*</span>
                      </template>
                    </VTextField>
                  </VCol>

                  <VCol cols="6">
                    <VAutocomplete
                      v-model="form.teacher_id"
                      :items="teacherList"
                      item-title="real_name"
                      item-value="teacher_id"
                      placeholder="请选择教师姓名"
                      label="教师姓名"
                    >
                      <template v-slot:label>
                        <span>教师姓名</span>
                      </template>
                    </VAutocomplete>
                  </VCol>
                  <VCol cols="12">
                    <VTextarea
                      type="textarea"
                      v-model="form.content"
                      label="教师职位描述"
                      placeholder="请输入评语"
                    >
                    </VTextarea>
                  </VCol>
                  <VDivider style="margin-top: 20px"/>
                  <VCol cols="12">
                    <div class="d-flex justify-end">
                      <VBtn
                        type="submit"
                        color="primary"
                        class="me-4"
                      >
                        添加
                      </VBtn>
                    </div>
                  </VCol>
                </VRow>

              </VForm>
            </VCardText>
          </PerfectScrollbar>
        </VCard>
      </div>
    </VDialog>
  </div>
</template>

<style lang="scss" scoped>

</style>
